import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, Input, Cell, CellGroup, Toast } from '@tarojs/components';
import './index.scss';
import { createPaymentOrderApi, queryPaymentOrderApi } from '../../api/payment';
import apiClient from '../../api/client';

interface BalanceInfo {
  balance: number;
  updated_at?: string;
}

// 预设充值金额选项
const RECHARGE_OPTIONS = [50, 100, 200, 500];

const BalanceRechargePage: React.FC = () => {
  const [balanceInfo, setBalanceInfo] = useState<BalanceInfo>({ balance: 0 });
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [customAmount, setCustomAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 获取用户余额信息
  useEffect(() => {
    fetchBalanceInfo();
  }, []);

  const fetchBalanceInfo = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/api/user/balance');
      
      if (response.code === 0) {
        setBalanceInfo(response.data);
      } else {
        setError(response.message || '获取余额失败');
        // 使用默认余额信息作为降级方案
        setBalanceInfo({ balance: 0 });
      }
    } catch (err) {
      console.error('获取余额信息失败:', err);
      setError('网络请求失败，请稍后重试');
      setBalanceInfo({ balance: 0 });
    } finally {
      setLoading(false);
    }
  };

  // 选择预设充值金额
  const handleSelectAmount = (amount: number) => {
    setSelectedAmount(amount);
    setCustomAmount('');
  };

  // 处理自定义金额输入
  const handleCustomAmountChange = (value: string) => {
    // 只允许输入数字和小数点
    const filteredValue = value.replace(/[^0-9.]/g, '');
    setCustomAmount(filteredValue);
    
    // 清除选中的预设金额
    setSelectedAmount(null);
  };

  // 验证充值金额
  const validateAmount = (amount: number): boolean => {
    if (isNaN(amount) || amount <= 0) {
      Toast({ title: '请输入有效的充值金额', icon: 'none' });
      return false;
    }
    
    if (amount < 1) {
      Toast({ title: '充值金额不能小于1元', icon: 'none' });
      return false;
    }
    
    if (amount > 5000) {
      Toast({ title: '单次充值金额不能超过5000元', icon: 'none' });
      return false;
    }
    
    return true;
  };

  // 处理充值提交
  const handleRecharge = async () => {
    try {
      // 确定充值金额
      let rechargeAmount: number;
      
      if (selectedAmount !== null) {
        rechargeAmount = selectedAmount;
      } else if (customAmount) {
        rechargeAmount = parseFloat(customAmount);
      } else {
        Toast({ title: '请选择或输入充值金额', icon: 'none' });
        return;
      }
      
      // 验证金额
      if (!validateAmount(rechargeAmount)) {
        return;
      }
      
      // 显示加载提示
      Taro.showLoading({ title: '正在创建订单...' });
      
      // 获取微信登录凭证
      await Taro.login({
        success: async(res) => {
          console.log('获取登录凭证成功:', res);
          await paymentOrder(rechargeAmount, res.code);
        },
        fail: err => {
          console.error('获取登录凭证失败:', err);
          Taro.showToast({
            title: '订单创建失败：获取微信凭证失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      Taro.hideLoading();
      console.error('充值过程出错:', error);
      Taro.showToast({
        title: '充值过程出错，请重试',
        icon: 'none'
      });
    }
  };
  
  // 创建支付订单并发起支付
  const paymentOrder = async (amount: number, code: string) => {
    try {
      // 调用后端接口创建支付订单
      const response = await createPaymentOrderApi({
        product_name: `账户余额充值-${amount}元`,
        price: amount,
        package_id: 0, // 余额充值不需要package_id
        code: code
      });
      
      // 隐藏加载提示
      Taro.hideLoading();
      
      if (response.code === 200) {
        // 从response.data中提取订单信息和支付参数
        const { order_info, pay_params } = response.data;
        
        // 调用微信支付，使用await等待支付结果
        const payResult = await Taro.requestPayment({
          ...pay_params,
          // Taro.requestPayment会返回Promise，不需要success/fail回调
        });
        
        // 支付成功后的处理
        console.log('支付成功:', payResult);
        
        // 支付成功后查询订单状态，确保余额更新
        Taro.showLoading({ title: '正在处理...' });
        
        // 实现重试机制确保订单状态查询的可靠性
        let queryAttempts = 0;
        const maxQueryAttempts = 3;
        const queryRetryDelay = 1000; // 1秒重试间隔
        let orderStatusConfirmed = false;
        let queryResponseData = null;
        
        while (queryAttempts < maxQueryAttempts && !orderStatusConfirmed) {
          try {
            const queryResponse = await queryPaymentOrderApi(order_info.out_trade_no);
            
            if (queryResponse.code === 0) {
              queryResponseData = queryResponse.data;
              const { trade_state } = queryResponseData;
              
              console.log(`订单状态查询第 ${queryAttempts + 1} 次结果:`, queryResponse.data);
              
              // 检查交易状态是否为最终状态
              const finalTradeStates = ['SUCCESS', 'PAYERROR', 'CLOSED', 'REVOKED'];
              
              if (finalTradeStates.includes(trade_state)) {
                orderStatusConfirmed = true;
                break;
              }
            } else {
              console.error(`订单查询第 ${queryAttempts + 1} 次失败:`, queryResponse.message);
            }
          } catch (queryError) {
            console.error(`订单状态查询第 ${queryAttempts + 1} 次遇到错误:`, queryError);
          }
          
          queryAttempts++;
          
          // 重试延迟
          if (queryAttempts < maxQueryAttempts && !orderStatusConfirmed) {
            await new Promise(resolve => setTimeout(resolve, queryRetryDelay));
          }
        }
        
        // 处理最终查询结果
        if (orderStatusConfirmed && queryResponseData?.trade_state === 'SUCCESS') {
          // 支付成功后的处理
          Taro.showToast({
            title: '充值成功',
            icon: 'success'
          });
          
          // 刷新余额信息
          await fetchBalanceInfo();
          
          // 返回上一页
          setTimeout(() => {
            Taro.navigateBack();
          }, 1500);
        } else {
          // 订单状态异常或查询失败
          const finalTradeState = queryResponseData?.trade_state || 'UNKNOWN';
          
          if (finalTradeState === 'UNKNOWN') {
            // 查询失败超过最大尝试次数
            console.error('订单状态查询超过最大尝试次数，最终状态未知');
            
            // 根据微信支付文档，即使查询失败，也应提示用户支付完成
            Taro.showToast({
              title: '充值完成，余额将稍后更新',
              icon: 'success'
            });
            setTimeout(() => {
              Taro.navigateBack();
            }, 1500);
          } else {
            // 支付失败或订单关闭
            console.error('支付失败，交易状态:', finalTradeState);
            Taro.showToast({
              title: `支付未完成: ${finalTradeState}`,
              icon: 'none'
            });
          }
        }
      }
      Taro.hideLoading();
    } catch (paymentError) {
      // 处理支付失败的情况
      console.log('支付失败:', paymentError);
      
      // 根据微信支付文档，支付失败包括用户取消支付和其他错误
      if (paymentError.errMsg === 'requestPayment:fail cancel') {
        // 用户取消支付
        Taro.showToast({
          title: '您已取消支付',
          icon: 'none'
        });
      } else {
        // 其他支付错误
        Taro.showToast({
          title: `支付失败: ${paymentError.errMsg}`,
          icon: 'none'
        });
      }
    }
  };

  return (
    <View className="balance-recharge-page">
      {/* 顶部标题栏 */}
      <View className="top-bar">
        <Button 
          className="back-btn" 
          plain 
          onClick={() => Taro.navigateBack()}
        >
          返回
        </Button>
        <Text className="page-title">余额充值</Text>
        <View className="placeholder"></View>
      </View>
      
      {/* 余额显示区域 */}
      <View className="balance-section">
        <Text className="balance-label">当前余额</Text>
        <Text className="balance-amount">¥{balanceInfo.balance.toFixed(2)}</Text>
        {balanceInfo.updated_at && (
          <Text className="update-time">更新时间: {balanceInfo.updated_at}</Text>
        )}
      </View>
      
      {/* 充值金额选择区域 */}
      <View className="recharge-section">
        <Text className="section-title">选择充值金额</Text>
        
        {/* 预设金额选项 */}
        <View className="amount-options">
          {RECHARGE_OPTIONS.map((amount) => (
            <View 
              key={amount}
              className={`amount-option ${selectedAmount === amount ? 'selected' : ''}`}
              onClick={() => handleSelectAmount(amount)}
            >
              <Text className="amount-text">¥{amount}</Text>
              {selectedAmount === amount && (
                <View className="selected-icon"></View>
              )}
            </View>
          ))}
        </View>
        
        {/* 自定义金额输入 */}
        <CellGroup className="custom-amount-group">
          <Cell>
            <View className="amount-input-wrapper">
              <Text className="currency-symbol">¥</Text>
              <Input
                className="amount-input"
                type="digit"
                placeholder="请输入自定义金额"
                value={customAmount}
                onChange={(e) => handleCustomAmountChange(e.detail.value)}
                onBlur={() => {
                  if (customAmount && parseFloat(customAmount) <= 0) {
                    setCustomAmount('');
                  }
                }}
              />
            </View>
          </Cell>
        </CellGroup>
        
        {/* 充值说明 */}
        <Text className="recharge-tips">
          说明：充值金额最低1元，最高5000元
        </Text>
      </View>
      
      {/* 底部充值按钮 */}
      <View className="bottom-section">
        <Button 
          className="recharge-button" 
          onClick={handleRecharge}
          loading={loading}
          disabled={!selectedAmount && !customAmount}
        >
          立即充值
        </Button>
      </View>
      
      {/* 错误提示 */}
      {error && (
        <View className="error-message">{error}</View>
      )}
    </View>
  );
};

export default BalanceRechargePage;